#include "../include/aj_tcpsession.h"
#include <QTimer>

NETAPI::TcpSession::TcpSession(TcpThread *thread)
{
    m_thread = thread;
    connect(this, &TcpSession::readyRead,
        this, &TcpSession::SlotStartRead);
    connect(this, &TcpSession::disconnected,
        this, &TcpSession::SlotDisConnected);
    connect(this, &TcpSession::SignalDoDisConnect,
        this, &TcpSession::SlotDoDisconnect);
    connect(this, &TcpSession::SignalDoWrite,
        this, &TcpSession::SlotDoWrite);
    connect(this, &TcpSession::SignalDoConnectToServer,
        this, &TcpSession::SlotDoConnectToServer);


}

NETAPI::TcpSession::~TcpSession()
{
    disconnect(this, &TcpSession::readyRead,
        this, &TcpSession::SlotStartRead);
    disconnect(this, &TcpSession::disconnected,
        this, &TcpSession::SlotDisConnected);
    disconnect(this, &TcpSession::SignalDoDisConnect,
        this, &TcpSession::SlotDoDisconnect);
    disconnect(this, &TcpSession::SignalDoWrite,
        this, &TcpSession::SlotDoWrite);
    disconnect(this, &TcpSession::SignalDoConnectToServer,
        this, &TcpSession::SlotDoConnectToServer);

}


void NETAPI::TcpSession::ConnectToServer(const QString &host,quint16 port)
{
    emit SignalDoConnectToServer(host, port);
}

void NETAPI::TcpSession::Disconnect()
{
    emit SignalDoDisConnect();
}

void NETAPI::TcpSession::Write(const char *data, qint64 len)
{
    m_writeBuffer_ = QByteArray(data, len);
    emit SignalDoWrite();
}

void NETAPI::TcpSession::SlotDoConnectToServer(const QString &host, quint16 port)
{
    this->connectToHost(QHostAddress(host), port);
}

void NETAPI::TcpSession::SlotStartRead()
{
    m_buffer = readAll();
    if (OnRead)
    {
        OnRead(m_buffer);
    }

    QThread::msleep(10);

    emit SignalRead(m_buffer, m_buffer.length());
}

void NETAPI::TcpSession::SlotDisConnected()
{
    if (m_thread)
        m_thread->SubOne();
    //通知会话断开连接
    if (OnDisConnected)
    {
        OnDisConnected(this);
    }
    //OnDisConnected(this);
    emit SignalDisConnected(this);//通知线程池断开该路连接
}

void NETAPI::TcpSession::SlotDoWrite()
{
    int length = write(m_writeBuffer_);

    int dataLength = m_writeBuffer_.length();
}

void NETAPI::TcpSession::SlotDoDisconnect()
{
    this->disconnectFromHost();
}
